// ===============================================
// error_utils
//
// Create by Will on 2020/10/5 6:09 PM
// Copyright @Will.All rights reserved.
// ===============================================

import 'dart:io';

import 'package:dio/dio.dart';

import '../../const/env_config.dart';
import '../exception/api_exception.dart';

class ErrorUtils {
  ErrorUtils._internal();
  static dynamic errorFrom(dynamic error) {
    dynamic originalError;

    switch (error.runtimeType) {
      case DioException:
        final dioError = error as DioException;
        originalError = dioError.error;
        break;
    }

    return originalError == null ? error : errorFrom(originalError);
  }

  static String? messageFrom(dynamic error) {
    final dynamic originalError = errorFrom(error);
    String? message;

    switch (originalError.runtimeType) {
      case DioException:
        final err = originalError as DioException;
        message = isErrorLog()
            ? '接口发生错误 ${err.requestOptions.path} 请求参数${err.requestOptions.data} ${err.requestOptions.queryParameters} 错误码 code=${err.response?.statusCode} 错误信息 message= ${err.message}'
            : err.message;

        break;
      case CoreKitAPIException:
        final apiException = originalError as CoreKitAPIException;
        message = apiException.message;
        break;
      case HttpException:
      case SocketException:
        message = '网络异常，请检查您的网络连接';
        break;
      default:
        message = '$originalError';
        break;
    }

    return message;
  }

  static int? apiExceptionCodeFrom(dynamic error) {
    final dynamic err = ErrorUtils.errorFrom(error);
    if (err is CoreKitAPIException) {
      return err.code;
    }

    return null;
  }
}
